from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from datetime import datetime

from app.api import deps
from app.schemas import vehicle_rental as schemas
from app.database.models.erp import VehicleRental, PackageOrder
from app.database.models.base import User

router = APIRouter()

@router.get("/", response_model=List[schemas.VehicleRental])
def list_vehicle_rentals(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    vehicle_type: Optional[str] = None,
    package_order_id: Optional[int] = None,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取车辆租赁订单列表"""
    try:
        query = db.query(VehicleRental)
        
        # 根据用户角色和工作区过滤
        if current_user.role == "agent":
            # agent只能查看自己工作区的订单
            query = query.filter(VehicleRental.work_area_id == current_user.workarea_id)
        elif current_user.role != "admin":
            # 非管理员且非agent的用户无权限查看
            raise HTTPException(
                status_code=403,
                detail="Not enough permissions to view vehicle rental orders"
            )
        
        # 添加过滤条件
        if vehicle_type:
            query = query.filter(VehicleRental.vehicle_type.like(f"%{vehicle_type}%"))
            
        # 按打包订单ID过滤
        if package_order_id is not None:
            if package_order_id <= 0:
                query = query.filter(VehicleRental.package_order_id == -1)
            else:
                query = query.filter(VehicleRental.package_order_id == package_order_id)
            
        # 添加排序和分页
        query = query.order_by(VehicleRental.rental_start_date.desc())
        rentals = query.offset(skip).limit(limit).all()
        
        return rentals
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Error fetching vehicle rentals: {str(e)}"
        )

@router.post("/", response_model=schemas.VehicleRental)
def create_vehicle_rental(
    *,
    db: Session = Depends(deps.get_db),
    rental_in: schemas.VehicleRentalCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新的车辆租赁订单"""
    try:
        # 使用当前用户的工作区ID
        rental_data = rental_in.dict()
        rental_data["work_area_id"] = current_user.workarea_id

        # 设置默认值
        if not rental_data.get("package_order_id") or rental_data["package_order_id"] <= 0:
            rental_data["package_order_id"] = -1
            rental_data["package_order_title"] = None
        else:
            # 如果关联了打包订单，查询订单标题
            package_order = db.query(PackageOrder).filter(
                PackageOrder.ID == rental_data["package_order_id"]
            ).first()
            if package_order:
                rental_data["package_order_title"] = package_order.title

        rental = VehicleRental(**rental_data)
        db.add(rental)
        db.commit()
        db.refresh(rental)
        return rental
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{rental_id}", response_model=schemas.VehicleRental)
def get_vehicle_rental(
    rental_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取特定车辆租赁订单详情"""
    try:
        rental = db.query(VehicleRental).filter(VehicleRental.ID == rental_id).first()
        if not rental:
            raise HTTPException(status_code=404, detail="Vehicle rental not found")

        # 如果关联了package_order，检查权限
        if rental.package_order_id:
            order = db.query(PackageOrder).filter(
                PackageOrder.ID == rental.package_order_id
            ).first()
            if current_user.role != "admin" and order.work_area_id != current_user.workarea_id:
                raise HTTPException(status_code=403, detail="Not enough permissions")

        return rental
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{rental_id}", response_model=schemas.VehicleRental)
def update_vehicle_rental(
    *,
    db: Session = Depends(deps.get_db),
    rental_id: int,
    rental_in: schemas.VehicleRentalUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新车辆租赁订单信息"""
    try:
        rental = db.query(VehicleRental).filter(VehicleRental.ID == rental_id).first()
        if not rental:
            raise HTTPException(status_code=404, detail="Vehicle rental not found")

        # 检查权限
        if current_user.role != "admin" and rental.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 更新租赁信息
        update_data = rental_in.dict(exclude_unset=True)
        for field, value in update_data.items():
            setattr(rental, field, value)

        db.add(rental)
        db.commit()
        db.refresh(rental)
        return rental
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{rental_id}", response_model=schemas.VehicleRental)
def delete_vehicle_rental(
    *,
    db: Session = Depends(deps.get_db),
    rental_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除车辆租赁订单"""
    try:
        # 先查询订单是否存在
        rental = db.query(VehicleRental).filter(VehicleRental.ID == rental_id).first()
        if not rental:
            raise HTTPException(status_code=404, detail="Vehicle rental not found")

        # 检查权限
        if current_user.role != "admin" and rental.work_area_id != current_user.workarea_id:
            raise HTTPException(status_code=403, detail="Not enough permissions")

        # 如果有关联的package_order，检查是否允许删除
        if rental.package_order_id and rental.package_order_id > 0:
            package_order = db.query(PackageOrder).filter(
                PackageOrder.ID == rental.package_order_id
            ).first()
            if package_order and package_order.status not in ["draft", "cancelled"]:
                raise HTTPException(
                    status_code=400,
                    detail="Cannot delete rental from a confirmed or completed package order"
                )

        # 执行删除
        db.delete(rental)
        db.commit()
        return rental
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e)) 